Popular Searches
Popular Course Categories
Popular Courses

Login, registration, and user authentication

Login, registration, and user authentication

Firebase with Flutter

Login, Registration, and User Authentication in Flutter

Authentication is an important part of modern Flutter applications. It allows an application to identify users, create accounts, securely log users in, maintain authentication sessions, and provide different features based on the signed-in user.

In Flutter applications, Firebase Authentication provides a convenient way to implement registration, login, logout, password recovery, email verification, and authentication-state management. Firebase provides an Authentication SDK and supports multiple authentication providers. For this module, we will focus mainly on email and password authentication.


1. What is User Authentication?

User authentication is the process of verifying the identity of a user before allowing access to protected features or data.

For example, when a user enters an email address and password, the authentication service verifies those credentials. If they are valid, the user is signed in.

Common Authentication Operations

  • Registration or Sign Up
  • Login or Sign In
  • Logout or Sign Out
  • Check Current User
  • Maintain Authentication State
  • Email Verification
  • Password Reset
  • Update User Profile
  • Change Password
  • Delete User Account

2. Authentication Flow in a Flutter Application

A typical authentication flow looks like this:

  1. User opens the Flutter application.
  2. The application checks whether a user is already authenticated.
  3. If no user is authenticated, the Login or Registration screen is displayed.
  4. The user creates an account using the Registration screen.
  5. Firebase creates the user account.
  6. The user can then log in using the registered credentials.
  7. After successful login, the application displays the authenticated area.
  8. The user can log out when finished.
Flutter App
    |
    v
Check Authentication State
    |
    +---- User Logged Out ----> Login / Registration
    |
    +---- User Logged In -----> Home / Dashboard
                                      |
                                      v
                                    Logout
                                      |
                                      v
                              Login / Registration

3. Why Use Firebase Authentication?

  • Provides ready-to-use authentication services.
  • Supports email and password authentication.
  • Supports multiple authentication providers.
  • Provides authentication state streams.
  • Provides password reset functionality.
  • Provides email verification.
  • Integrates with other Firebase services.
  • Each authenticated user receives a unique Firebase user ID.

Firebase Authentication can also integrate with services such as Firestore, Realtime Database, and Cloud Storage so that application data can be associated with authenticated users.


4. Prerequisites

Before implementing authentication, you should have:

  • Flutter SDK installed.
  • A Flutter project.
  • A Firebase project.
  • Firebase configured with the Flutter application.
  • Email/Password authentication enabled in Firebase Console.

Official Firebase Flutter setup documentation:

Firebase Flutter Setup Documentation


5. Add Firebase Authentication to Flutter

Add the Firebase Authentication package to your Flutter project:

flutter pub add firebase_auth

Then import the package:

import 'package:firebase_auth/firebase_auth.dart';

Firebase should be configured in the Flutter project before using Firebase Authentication.


6. Enable Email and Password Authentication

After configuring Firebase, enable Email/Password authentication from the Firebase Console.

  1. Open Firebase Console.
  2. Select your Firebase project.
  3. Open Authentication.
  4. Open the Sign-in method section.
  5. Select Email/Password.
  6. Enable Email/Password authentication.
  7. Save the configuration.

The official Firebase documentation provides the current configuration steps for Flutter authentication.


7. FirebaseAuth Instance

The FirebaseAuth class provides methods for authentication operations.

final FirebaseAuth auth = FirebaseAuth.instance;

You can also directly use:

FirebaseAuth.instance

For example:

final user = FirebaseAuth.instance.currentUser;

8. User Registration

Registration, also called Sign Up, allows a new user to create an account.

For email and password authentication, Firebase provides the createUserWithEmailAndPassword() method.

final credential = await FirebaseAuth.instance
    .createUserWithEmailAndPassword(
  email: email,
  password: password,
);

When registration succeeds, Firebase creates the account and the newly created user is signed in.


9. Basic Registration Example

Future registerUser(String email, String password) async {
  try {
    final credential = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(
      email: email,
      password: password,
    );

    print('Registration successful');
    print('User ID: ${credential.user?.uid}');
  } on FirebaseAuthException catch (e) {
    print('Registration error: ${e.code}');
  } catch (e) {
    print('Unexpected error: $e');
  }
}

10. Registration Form in Flutter

A registration form generally contains:

  • Name field
  • Email field
  • Password field
  • Confirm password field
  • Register button
  • Link to the Login screen
final emailController = TextEditingController();
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();

Registration Button

ElevatedButton(
  onPressed: () async {
    final email = emailController.text.trim();
    final password = passwordController.text.trim();
    final confirmPassword = confirmPasswordController.text.trim();

    if (password != confirmPassword) {
      print('Passwords do not match');
      return;
    }

    await registerUser(email, password);
  },
  child: const Text('Register'),
)

11. Registration Validation

Validation should be performed before sending user information to Firebase.

Basic Validation Example

bool validateRegistration(
  String email,
  String password,
  String confirmPassword,
) {
  if (email.isEmpty) {
    return false;
  }

  if (password.isEmpty) {
    return false;
  }

  if (password != confirmPassword) {
    return false;
  }

  return true;
}

Recommended Validation

  • Email should not be empty.
  • Email should have a valid format.
  • Password should meet your application's requirements.
  • Confirm password should match the password.
  • Submit button should be disabled or protected while registration is processing.

12. Login

Login, also called Sign In, allows an existing user to access the application.

Firebase provides the signInWithEmailAndPassword() method for email/password login.

final credential = await FirebaseAuth.instance
    .signInWithEmailAndPassword(
  email: email,
  password: password,
);

13. Basic Login Function

Future loginUser(String email, String password) async {
  try {
    final credential = await FirebaseAuth.instance
        .signInWithEmailAndPassword(
      email: email,
      password: password,
    );

    print('Login successful');
    print('User ID: ${credential.user?.uid}');
  } on FirebaseAuthException catch (e) {
    print('Login error: ${e.code}');
  } catch (e) {
    print('Unexpected error: $e');
  }
}

14. Login Form

A typical login screen contains an email field, password field, login button, forgot-password option, and registration option.

final emailController = TextEditingController();
final passwordController = TextEditingController();

Login Button

ElevatedButton(
  onPressed: () async {
    final email = emailController.text.trim();
    final password = passwordController.text.trim();

    await loginUser(email, password);
  },
  child: const Text('Login'),
)

15. Complete Login Screen Example

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State createState() => _LoginScreenState();
}

class _LoginScreenState extends State {
  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  bool loading = false;

  Future login() async {
    setState(() {
      loading = true;
    });

    try {
      await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: emailController.text.trim(),
        password: passwordController.text.trim(),
      );

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Login successful')),
      );
    } on FirebaseAuthException catch (e) {
      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Login failed: ${e.code}')),
      );
    } finally {
      if (mounted) {
        setState(() {
          loading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Login'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              controller: emailController,
              keyboardType: TextInputType.emailAddress,
              decoration: const InputDecoration(
                labelText: 'Email',
              ),
            ),
            TextField(
              controller: passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: 'Password',
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: loading ? null : login,
              child: loading
                  ? const CircularProgressIndicator()
                  : const Text('Login'),
            ),
          ],
        ),
      ),
    );
  }
}

16. Logout

When a user wants to leave the authenticated session, call signOut().

await FirebaseAuth.instance.signOut();

Logout Function

Future logout() async {
  await FirebaseAuth.instance.signOut();
}

After logout, the authentication state changes and the application can display the login screen.


17. Get the Current User

Firebase provides currentUser to access the currently signed-in user.

final User? user = FirebaseAuth.instance.currentUser;

You can check whether a user is logged in:

if (FirebaseAuth.instance.currentUser != null) {
  print('User is logged in');
} else {
  print('User is logged out');
}

18. Firebase User Object

The authenticated user is represented by the User object.

final user = FirebaseAuth.instance.currentUser;

print(user?.uid);
print(user?.email);
print(user?.displayName);
print(user?.photoURL);
print(user?.emailVerified);

Common User Properties

Property Description
uid Unique identifier of the Firebase user.
email Email address associated with the account.
displayName User's display name.
photoURL URL of the user's profile image.
emailVerified Indicates whether the email address has been verified.
phoneNumber Phone number associated with the user when applicable.

19. Authentication State

An application often needs to know whether the user is currently logged in or logged out.

Firebase Authentication provides authentication-state streams for this purpose.

FirebaseAuth.instance.authStateChanges().listen((User? user) {
  if (user == null) {
    print('User is signed out');
  } else {
    print('User is signed in');
  }
});

The authentication stream can be used to automatically switch between Login and Home screens.


20. Using StreamBuilder for Authentication

StreamBuilder is useful when the UI needs to react automatically to authentication changes.

class AuthGate extends StatelessWidget {
  const AuthGate({super.key});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }

        if (snapshot.hasData) {
          return const HomeScreen();
        }

        return const LoginScreen();
      },
    );
  }
}

21. Authentication Gate

An authentication gate is a widget that decides which screen should be displayed based on the current authentication state.

MaterialApp(
  home: const AuthGate(),
);

The basic logic is:

User authenticated
        |
        +---- Yes ----> HomeScreen
        |
        +---- No -----> LoginScreen

22. authStateChanges()

authStateChanges() provides a stream that notifies the application when the authentication state changes, such as when a user signs in or signs out.

FirebaseAuth.instance.authStateChanges()

This is commonly used to control the application's Login and Home screens.


23. idTokenChanges() and userChanges()

Firebase Authentication also provides other authentication-related streams.

FirebaseAuth.instance.idTokenChanges();

FirebaseAuth.instance.userChanges();

Use the stream that matches the type of authentication-state or user-change information your application needs.


24. Email Verification

Email verification allows an application to ask the user to confirm ownership of the registered email address.

final user = FirebaseAuth.instance.currentUser;
await user?.sendEmailVerification();

You can check the verification status:

final user = FirebaseAuth.instance.currentUser;

if (user?.emailVerified == true) {
  print('Email verified');
} else {
  print('Email not verified');
}

25. Password Reset

A Forgot Password feature allows users to reset their password through an email.

await FirebaseAuth.instance.sendPasswordResetEmail(
  email: email,
);

Password Reset Flow

  1. User selects Forgot Password.
  2. User enters their email address.
  3. Flutter sends a password-reset request to Firebase.
  4. Firebase sends the reset email.
  5. User follows the instructions in the email.
  6. User creates a new password.

26. Update User Profile

After registration or login, an application may allow the user to update profile information.

Update Display Name

final user = FirebaseAuth.instance.currentUser;
await user?.updateDisplayName('John Doe');

Update Photo URL

await user?.updatePhotoURL(
  'https://example.com/profile.jpg',
);

27. Change Password

An authenticated user can change their password using updatePassword().

final user = FirebaseAuth.instance.currentUser;
await user?.updatePassword('NewStrongPassword123!');

Some sensitive account operations may require recent authentication. In those situations, Firebase can require the user to sign in again before completing the operation.


28. Delete User Account

A user account can be deleted when your application provides an account-deletion feature.

final user = FirebaseAuth.instance.currentUser;
await user?.delete();

For security-sensitive operations, Firebase may require recent authentication before the operation is allowed.


29. Authentication Error Handling

Authentication operations should always handle errors gracefully.

try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: email,
    password: password,
  );
} on FirebaseAuthException catch (e) {
  print(e.code);
  print(e.message);
}

Common Registration Errors

Error Meaning
weak-password The password does not meet Firebase's password requirements.
email-already-in-use An account already exists with the provided email.
invalid-email The email address is invalid.

Common Login Errors

Error Meaning
user-not-found No matching user was found for the provided credentials.
wrong-password The supplied password is incorrect for the account.
invalid-email The email address is invalid.
user-disabled The user account has been disabled.

Error codes and behavior can change with Firebase SDK versions and authentication configuration, so application code should handle errors based on the current Firebase documentation.


30. User-Friendly Error Messages

Technical Firebase error codes should not normally be displayed directly to end users.

String getAuthErrorMessage(String code) {
  switch (code) {
    case 'invalid-email':
      return 'Please enter a valid email address.';
    case 'user-not-found':
      return 'No account was found with this email.';
    case 'wrong-password':
      return 'The password is incorrect.';
    case 'email-already-in-use':
      return 'An account already exists with this email.';
    case 'weak-password':
      return 'Please choose a stronger password.';
    default:
      return 'Authentication failed. Please try again.';
  }
}

31. Loading State During Login

Authentication requests are asynchronous. A loading indicator should be displayed while the request is processing.

bool isLoading = false;

Future login() async {
  setState(() {
    isLoading = true;
  });

  try {
    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: emailController.text.trim(),
      password: passwordController.text.trim(),
    );
  } finally {
    if (mounted) {
      setState(() {
        isLoading = false;
      });
    }
  }
}

Disabling the login button during the request also helps prevent accidental multiple submissions.


32. Complete Authentication Service

Authentication logic can be separated from UI code by creating an authentication service.

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  Future register(
    String email,
    String password,
  ) {
    return _auth.createUserWithEmailAndPassword(
      email: email,
      password: password,
    );
  }

  Future login(
    String email,
    String password,
  ) {
    return _auth.signInWithEmailAndPassword(
      email: email,
      password: password,
    );
  }

  Future logout() {
    return _auth.signOut();
  }

  User? get currentUser {
    return _auth.currentUser;
  }

  Stream get authStateChanges {
    return _auth.authStateChanges();
  }
}

33. Using AuthService

final authService = AuthService();

await authService.register(
  '[email protected]',
  'Password123!',
);

await authService.login(
  '[email protected]',
  'Password123!',
);

await authService.logout();

This approach keeps authentication operations separate from widgets and makes the application easier to maintain.


34. Recommended Project Structure

lib/
├── main.dart
├── firebase_options.dart
├── screens/
│   ├── login_screen.dart
│   ├── register_screen.dart
│   ├── forgot_password_screen.dart
│   └── home_screen.dart
├── services/
│   └── auth_service.dart
├── widgets/
│   ├── custom_text_field.dart
│   └── auth_button.dart
└── models/
    └── user_model.dart

For larger applications, authentication logic can also be organized using repositories, controllers, providers, BLoC, Riverpod, or another state-management architecture.


35. Registration and Login with Form Validation

Flutter's Form and TextFormField widgets can be used to validate user input.

final formKey = GlobalKey();

Form(
  key: formKey,
  child: Column(
    children: [
      TextFormField(
        decoration: const InputDecoration(
          labelText: 'Email',
        ),
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Email is required';
          }
          return null;
        },
      ),
      TextFormField(
        obscureText: true,
        decoration: const InputDecoration(
          labelText: 'Password',
        ),
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Password is required';
          }
          return null;
        },
      ),
    ],
  ),
)

Before submitting:

if (formKey.currentState!.validate()) {
  // Perform authentication
}

36. Login and Registration Navigation

A common application structure contains separate Login and Registration screens.

Login Screen
    |
    +---- Register --------> Registration Screen
    |
    +---- Forgot Password -> Password Reset Screen

Registration Screen
    |
    +---- Successful Registration -> Home Screen

Login Screen
    |
    +---- Successful Login --------> Home Screen

With an authentication gate, explicit navigation after every authentication event is often unnecessary because the authentication stream can automatically rebuild the appropriate screen.


37. Login Screen UI Example

Column(
  children: [
    TextFormField(
      controller: emailController,
      decoration: const InputDecoration(
        labelText: 'Email',
        prefixIcon: Icon(Icons.email),
      ),
    ),
    TextFormField(
      controller: passwordController,
      obscureText: true,
      decoration: const InputDecoration(
        labelText: 'Password',
        prefixIcon: Icon(Icons.lock),
      ),
    ),
    const SizedBox(height: 20),
    ElevatedButton(
      onPressed: login,
      child: const Text('Login'),
    ),
    TextButton(
      onPressed: () {
        // Navigate to registration
      },
      child: const Text('Create an account'),
    ),
    TextButton(
      onPressed: () {
        // Navigate to forgot password
      },
      child: const Text('Forgot Password?'),
    ),
  ],
)

38. Registration Screen UI Example

Column(
  children: [
    TextFormField(
      controller: nameController,
      decoration: const InputDecoration(
        labelText: 'Full Name',
      ),
    ),
    TextFormField(
      controller: emailController,
      decoration: const InputDecoration(
        labelText: 'Email',
      ),
    ),
    TextFormField(
      controller: passwordController,
      obscureText: true,
      decoration: const InputDecoration(
        labelText: 'Password',
      ),
    ),
    TextFormField(
      controller: confirmPasswordController,
      obscureText: true,
      decoration: const InputDecoration(
        labelText: 'Confirm Password',
      ),
    ),
    const SizedBox(height: 20),
    ElevatedButton(
      onPressed: register,
      child: const Text('Register'),
    ),
  ],
)

39. Authentication with Firestore User Profiles

Firebase Authentication stores authentication information, while Cloud Firestore can be used to store additional application-specific profile information.

For example, after registration, an application might store:

  • User ID
  • Full name
  • Email
  • Phone number
  • Profile image URL
  • Created date
users
 └── USER_UID
     ├── name
     ├── email
     ├── phone
     └── createdAt

The Firebase Authentication uid can be used as the document ID so that a profile is directly associated with the authenticated account.


40. Example Firestore User Profile

final user = FirebaseAuth.instance.currentUser;

if (user != null) {
  await FirebaseFirestore.instance
      .collection('users')
      .doc(user.uid)
      .set({
    'name': 'John Doe',
    'email': user.email,
    'createdAt': FieldValue.serverTimestamp(),
  });
}

If you use this example, add the Cloud Firestore package:

flutter pub add cloud_firestore

41. Authentication and Security Rules

Authentication can be combined with Firebase Security Rules to restrict access to data.

A common concept is allowing a user to access only their own document.

match /users/{userId} {
  allow read, write: if request.auth != null
                     && request.auth.uid == userId;
}

This means the request must come from an authenticated user and the authenticated user's UID must match the requested document ID.


42. Multiple Authentication Providers

Firebase Authentication supports multiple authentication methods, depending on your project requirements and configuration.

Examples include:

  • Email and Password
  • Google Sign-In
  • Phone Authentication
  • Email Link Authentication
  • Anonymous Authentication
  • Other supported identity providers

The authentication provider must be enabled and configured before it can be used in the application.


43. Google Sign-In Concept

Google Sign-In allows users to authenticate using their Google account instead of creating a separate password for your application.

The general flow is:

User
  |
  v
Tap "Continue with Google"
  |
  v
Google Authentication
  |
  v
Google Credential
  |
  v
Firebase Authentication
  |
  v
Authenticated User

When multiple authentication providers are linked to one Firebase account, the same Firebase user ID can identify the user across the linked providers.


44. Email Link Authentication

Firebase also supports passwordless email-link authentication. The user receives an authentication link through email and uses that link to complete the sign-in process.

FirebaseAuth.instance.sendSignInLinkToEmail(
  email: email,
  actionCodeSettings: actionCodeSettings,
);

Email-link authentication is different from traditional email/password login because the user does not need to enter a password during the sign-in flow.


45. Anonymous Authentication

Anonymous authentication can be useful when an application wants to give a user access to certain features without requiring immediate registration.

Later, an anonymous account can potentially be linked to another authentication provider so that the user can continue with the same Firebase account.


46. Linking Authentication Providers

Firebase allows supported authentication credentials to be linked to an existing account.

// Conceptual example
final user = FirebaseAuth.instance.currentUser;

// Link a provider credential to the current user.
// The credential is obtained from the selected provider.

Account linking can allow a user who initially registered with one provider to use another supported provider with the same Firebase user account.


47. Reauthentication

Some sensitive operations may require the user to have authenticated recently.

For example, changing sensitive account information or deleting an account may require recent authentication.

The general flow is:

Existing User
     |
     v
Reauthenticate
     |
     v
Sensitive Operation
     |
     v
Success

48. Authentication State Flow in a Real Application

App Starts
   |
   v
FirebaseAuth.authStateChanges()
   |
   +----------------------+
   |                      |
   v                      v
User == null          User != null
   |                      |
   v                      v
Login Screen          Home Screen
   |                      |
   |                      v
   |                    Logout
   |                      |
   +----------<-----------+
              |
              v
        Login Screen

49. Complete AuthGate Example

class AuthGate extends StatelessWidget {
  const AuthGate({super.key});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }

        final user = snapshot.data;

        if (user != null) {
          return const HomeScreen();
        }

        return const LoginScreen();
      },
    );
  }
}

50. Main Application Example

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const AuthGate(),
    );
  }
}

If your Firebase project uses generated Flutter configuration, initialize Firebase with the generated platform-specific options according to the current Firebase Flutter setup documentation.


51. Authentication Best Practices

  • Never store plain-text passwords in Firestore or another database.
  • Use Firebase Authentication rather than creating your own password storage system unnecessarily.
  • Validate form fields before sending authentication requests.
  • Show appropriate loading states.
  • Handle Firebase authentication errors.
  • Do not expose sensitive credentials in source code.
  • Use Firebase Security Rules to protect application data.
  • Use email verification when your application requires verified email ownership.
  • Use strong password requirements appropriate to your application.
  • Use recent authentication requirements for sensitive account operations.
  • Keep authentication logic separate from UI when the application becomes larger.
  • Do not rely only on client-side checks for protecting backend data.

52. Common Authentication Mistakes

Mistake Better Approach
Not enabling the authentication provider Enable the required provider in Firebase Console.
Not handling exceptions Use FirebaseAuthException and display useful messages.
Calling authentication repeatedly from build() Perform operations in event handlers or appropriate state-management logic.
Not showing loading state Disable repeated submissions and show progress.
Storing passwords manually Use Firebase Authentication.
Ignoring authentication state Use authStateChanges() or another appropriate stream.
Weak database rules Use authenticated-user and UID-based access rules.
Putting all authentication code in one widget Move authentication operations into a service or repository.

53. Login vs Registration

Feature Registration Login
Purpose Create a new account Access an existing account
Firebase Method createUserWithEmailAndPassword() signInWithEmailAndPassword()
Existing Account Normally not required Required
Typical Inputs Email, password, confirmation Email and password
Result New authenticated user Authenticated existing user

54. Authentication Components

Component Purpose
FirebaseAuth Main Firebase Authentication API.
User Represents an authenticated Firebase user.
createUserWithEmailAndPassword() Creates a new email/password account.
signInWithEmailAndPassword() Signs an existing user in.
signOut() Signs the current user out.
currentUser Provides the current authenticated user, when available.
authStateChanges() Provides authentication-state changes as a stream.
sendPasswordResetEmail() Sends a password-reset email.
sendEmailVerification() Sends an email verification message.
updatePassword() Updates the user's password.
delete() Deletes the authenticated user's account.

55. Mini Project: Flutter Authentication App

Create a simple authentication application with the following screens:

  • Splash or Auth Gate
  • Login
  • Registration
  • Forgot Password
  • Home
  • Profile

Required Features

  1. Create a Firebase project.
  2. Connect the Flutter application to Firebase.
  3. Add firebase_auth.
  4. Enable Email/Password authentication.
  5. Create the Registration screen.
  6. Validate registration fields.
  7. Create user accounts with Firebase.
  8. Create the Login screen.
  9. Authenticate users using email and password.
  10. Display a loading indicator during authentication.
  11. Display friendly authentication errors.
  12. Create an AuthGate.
  13. Display the Home screen for authenticated users.
  14. Implement Logout.
  15. Implement Forgot Password.
  16. Implement email verification if required.

56. Suggested Mini Project Structure

lib/
├── main.dart
├── firebase_options.dart
├── screens/
│   ├── login_screen.dart
│   ├── register_screen.dart
│   ├── forgot_password_screen.dart
│   ├── home_screen.dart
│   └── profile_screen.dart
├── services/
│   └── auth_service.dart
└── widgets/
    ├── auth_text_field.dart
    └── auth_button.dart

57. Practical Authentication Example

Future register(
  String email,
  String password,
) async {
  try {
    await FirebaseAuth.instance.createUserWithEmailAndPassword(
      email: email.trim(),
      password: password,
    );

    print('Account created successfully');
  } on FirebaseAuthException catch (e) {
    print('Registration failed: ${e.code}');
  }
}

Future login(
  String email,
  String password,
) async {
  try {
    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: email.trim(),
      password: password,
    );

    print('Logged in successfully');
  } on FirebaseAuthException catch (e) {
    print('Login failed: ${e.code}');
  }
}

Future logout() async {
  await FirebaseAuth.instance.signOut();
}

58. Authentication Interview Questions

  1. What is authentication in Flutter?
  2. What is Firebase Authentication?
  3. How do you add Firebase Authentication to a Flutter project?
  4. What is the purpose of FirebaseAuth.instance?
  5. How do you register a user using email and password?
  6. How do you log in a user using Firebase Authentication?
  7. How do you log out a user?
  8. What is currentUser?
  9. What is authStateChanges()?
  10. Why is StreamBuilder useful for authentication?
  11. How do you implement Forgot Password?
  12. How do you send an email verification message?
  13. What is the difference between login and registration?
  14. How should Firebase authentication errors be handled?
  15. Why should passwords not be stored manually in Firestore?
  16. What is an authentication gate?
  17. How can Firebase Authentication be combined with Firestore?
  18. What is the purpose of a Firebase user's UID?
  19. What are authentication providers?
  20. Why is recent authentication important for sensitive operations?

59. Quick Revision

Task Flutter/Firebase Method
Create account createUserWithEmailAndPassword()
Login signInWithEmailAndPassword()
Logout signOut()
Current user currentUser
Authentication state authStateChanges()
Password reset sendPasswordResetEmail()
Email verification sendEmailVerification()
Update name updateDisplayName()
Update photo updatePhotoURL()
Update password updatePassword()
Delete account delete()

60. Learning Outcome

After completing this topic, you should be able to:

  • Explain authentication and authorization concepts.
  • Configure Firebase Authentication in a Flutter application.
  • Create a user registration system.
  • Create a login system.
  • Implement logout functionality.
  • Check the currently authenticated user.
  • Manage authentication state.
  • Create an authentication gate.
  • Validate login and registration forms.
  • Handle Firebase authentication errors.
  • Implement password reset functionality.
  • Implement email verification.
  • Manage basic user profile information.
  • Connect authenticated users with Firestore data.
  • Apply UID-based security rules.
  • Structure authentication code using services and reusable components.

61. Official Resources


62. JustAcademy Flutter Resources

For structured Flutter learning and practical training, explore the following resources:


63. Summary

Login, registration, and user authentication are essential features for applications that provide personalized or protected functionality. In Flutter, Firebase Authentication can be used to create accounts, sign users in and out, monitor authentication state, reset passwords, verify emails, manage user profiles, and connect authenticated identities with Firebase data.

A typical implementation consists of a Registration screen, Login screen, Forgot Password screen, authentication service, AuthGate, Home screen, and appropriate error and loading-state handling. For production applications, authentication should be combined with secure Firebase configuration, appropriate Security Rules, input validation, and careful handling of sensitive operations.

whatsapp